<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户认证</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .active { color: #4285f4; border-bottom: 2px solid #4285f4; }
        .form-focus { box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.25); border-color: #4285f4; }
        .strength-weak { width: 25%; background-color: #ff4d4f; }
        .strength-medium { width: 50%; background-color: #faad14; }
        .strength-strong { width: 100%; background-color: #52c41a; }
        .message { padding: 0.5rem 1rem; border-radius: 0.375rem; margin-bottom: 1rem; }
        .message-success { background-color: #d1fae5; color: #065f46; }
        .message-error { background-color: #fee2e2; color: #b91c1c; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-lg shadow-md max-w-md w-full overflow-hidden">
        <!-- 标签页导航 -->
        <div class="flex border-b">
            <button id="login-tab" class="active flex-1 py-3 px-4 text-center font-medium" onclick="switchTab('login')">登录</button>
            <button id="register-tab" class="text-gray-500 flex-1 py-3 px-4 text-center font-medium" onclick="switchTab('register')">注册</button>
        </div>
        <!-- 登录表单 -->
        <div id="login-form" class="tab-content p-5 active">
            <div id="login-message" class="hidden message"></div>
            <form id="loginForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">用户名</label>
                    <div class="relative">
                        <input type="text" id="login-username" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入用户名" required>
                        <i class="fa fa-user absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">密码</label>
                    <div class="relative">
                        <input type="password" id="login-password" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入密码" required>
                        <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">验证码</label>
                    <div class="flex space-x-2">
                        <div class="relative flex-1">
                            <input type="text" id="login-captcha" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入验证码" required>
                            <i class="fa fa-shield absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <div class="w-24 h-10">
                            <canvas id="login-captcha-canvas" class="w-full h-full border rounded-md cursor-pointer" onclick="refreshCaptcha('login')"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="flex items-center justify-between">
                    <label class="flex items-center">
                        <input type="checkbox" id="remember-me" class="h-4 w-4 text-blue-500">
                        <span class="ml-2 text-sm text-gray-600">记住密码</span>
                    </label>
                    <button type="button" onclick="switchTab('forgot')" class="text-sm text-blue-500 hover:text-blue-600">忘记密码?</button>
                </div>
                
                <button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded-md font-medium hover:bg-blue-600">登录</button>
                
                <div class="text-center text-sm">
                    <span class="text-gray-600">还没有账号?</span>
                    <button type="button" onclick="switchTab('register')" class="text-blue-500 hover:text-blue-600 font-medium">立即注册</button>
                </div>
            </form>
        </div>
        <!-- 注册表单 -->
        <div id="register-form" class="tab-content p-5">
            <div id="register-message" class="hidden message"></div>
            <form id="registerForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700">用户名</label>
                    <div class="relative">
                        <input type="text" id="reg-username" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="4-16位字母或数字" required>
                        <i class="fa fa-user-plus absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">密码</label>
                    <div class="relative">
                        <input type="password" id="reg-password" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="6-20位字符" required>
                        <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div class="mt-1 h-1.5 bg-gray-200 rounded-full">
                        <div id="reg-strength" class="h-full rounded-full strength-weak"></div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">确认密码</label>
                    <div class="relative">
                        <input type="password" id="reg-confirm-password" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="再次输入密码" required>
                        <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">电子邮箱</label>
                    <div class="relative">
                        <input type="email" id="reg-email" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入有效邮箱" required>
                        <i class="fa fa-envelope absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">验证码</label>
                    <div class="flex space-x-2">
                        <div class="relative flex-1">
                            <input type="text" id="reg-captcha" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入验证码" required>
                            <i class="fa fa-shield absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <div class="w-24 h-10">
                            <canvas id="reg-captcha-canvas" class="w-full h-full border rounded-md cursor-pointer" onclick="refreshCaptcha('reg')"></canvas>
                        </div>
                    </div>
                </div>
                
                <button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded-md font-medium hover:bg-blue-600">注册</button>
                
                <div class="text-center text-sm">
                    <span class="text-gray-600">已有账号?</span>
                    <button type="button" onclick="switchTab('login')" class="text-blue-500 hover:text-blue-600 font-medium">立即登录</button>
                </div>
            </form>
        </div>
        <!-- 忘记密码表单 -->
        <div id="forgot-form" class="tab-content p-5">
            <div id="forgot-message" class="hidden message"></div>
            <form id="forgotForm" class="space-y-4">
                <div>
                    <h3 class="text-lg font-medium text-gray-800 mb-4">重置密码</h3>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">电子邮箱</label>
                    <div class="relative">
                        <input type="email" id="forgot-email" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入注册邮箱" required>
                        <i class="fa fa-envelope absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">验证码</label>
                    <div class="flex space-x-2">
                        <div class="relative flex-1">
                            <input type="text" id="forgot-code" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="请输入邮箱验证码" required>
                            <i class="fa fa-key absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <button type="button" id="send-code-btn" class="verify-btn flex-shrink-0 bg-blue-500 text-white py-2 px-4 rounded-md font-medium hover:bg-blue-600">获取验证码</button>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">新密码</label>
                    <div class="relative">
                        <input type="password" id="forgot-password" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="设置新密码" required>
                        <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700">确认新密码</label>
                    <div class="relative">
                        <input type="password" id="forgot-confirm-password" class="w-full pl-10 pr-3 py-2 border rounded-md focus:outline-none form-focus" placeholder="再次输入新密码" required>
                        <i class="fa fa-lock absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                </div>
                
                <div class="flex space-x-3">
                    <button type="button" onclick="switchTab('login')" class="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md font-medium hover:bg-gray-300">返回登录</button>
                    <button type="submit" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-md font-medium hover:bg-blue-600">重置密码</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        // 本地存储相关函数
        const USER_STORAGE_KEY = 'auth_users';
        const CURRENT_USER_KEY = 'current_user';
        const EMAIL_CODE_KEY = 'email_code';
        
        // 获取所有用户数据
        function getUsers() {
            const users = localStorage.getItem(USER_STORAGE_KEY);
            return users ? JSON.parse(users) : [];
        }
        
        // 保存用户数据
        function saveUsers(users) {
            localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(users));
        }
        
        // 保存当前用户
        function saveCurrentUser(user) {
            localStorage.setItem(CURRENT_USER_KEY, JSON.stringify(user));
        }
        
        // 简单加密函数
        function encrypt(text) {
            return btoa(text);
        }
        
        // 简单解密函数
        function decrypt(encryptedText) {
            return atob(encryptedText);
        }
        
        // 切换标签页
        function switchTab(tabName) {
            // 更新标签样式
            document.querySelectorAll('#login-tab, #register-tab').forEach(tab => {
                tab.classList.remove('active');
                tab.classList.add('text-gray-500');
            });
            document.getElementById(`${tabName}-tab`)?.classList.add('active');
            document.getElementById(`${tabName}-tab`)?.classList.remove('text-gray-500');
            
            // 显示对应内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(`${tabName}-form`)?.classList.add('active');
            
            // 刷新验证码
            if (tabName === 'login' || tabName === 'register') {
                refreshCaptcha(tabName === 'login' ? 'login' : 'reg');
            }
        }
        // 生成验证码
        function generateCaptcha(canvasId) {
            const canvas = document.getElementById(canvasId);
            if (!canvas) return;
            
            canvas.width = 80;
            canvas.height = 30;
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 生成4位验证码
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            let code = '';
            for (let i = 0; i < 4; i++) {
                code += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            localStorage.setItem('captcha', code);
            
            // 绘制背景和文字
            ctx.fillStyle = '#f5f5f5';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.font = '16px Arial';
            ctx.fillStyle = '#333';
            
            for (let i = 0; i < 4; i++) {
                ctx.fillText(code[i], 18 * i + 8, 20);
            }
            
            // 绘制干扰线
            ctx.strokeStyle = '#ddd';
            for (let i = 0; i < 3; i++) {
                ctx.beginPath();
                ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.stroke();
            }
        }
        // 刷新验证码
        function refreshCaptcha(type) {
            const canvasId = type === 'login' ? 'login-captcha-canvas' : 'reg-captcha-canvas';
            generateCaptcha(canvasId);
        }
        // 检查密码强度
        function checkPasswordStrength(password) {
            const strengthEl = document.getElementById('reg-strength');
            if (!strengthEl || !password) return;
            
            let score = 0;
            if (password.length >= 6) score += 1;
            if (/[a-z]/.test(password)) score += 1;
            if (/[A-Z]/.test(password)) score += 1;
            if (/[0-9]/.test(password)) score += 1;
            if (/[^a-zA-Z0-9]/.test(password)) score += 1;
            
            if (score <= 2) {
                strengthEl.className = 'h-full rounded-full strength-weak';
            } else if (score <= 3) {
                strengthEl.className = 'h-full rounded-full strength-medium';
            } else {
                strengthEl.className = 'h-full rounded-full strength-strong';
            }
        }
        
        // 显示消息
        function showMessage(messageId, message, isError = false) {
            const messageEl = document.getElementById(messageId);
            messageEl.textContent = message;
            messageEl.className = `message ${isError ? 'message-error' : 'message-success'} block`;
            
            // 3秒后隐藏消息
            setTimeout(() => {
                messageEl.classList.add('hidden');
            }, 3000);
        }
        // 生成随机验证码
        function generateEmailCode() {
            const chars = '0123456789';
            let code = '';
            for (let i = 0; i < 6; i++) {
                code += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return code;
        }
        // 表单提交
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化验证码
            generateCaptcha('login-captcha-canvas');
            generateCaptcha('reg-captcha-canvas');
            
            // 密码强度检测
            document.getElementById('reg-password')?.addEventListener('input', function() {
                checkPasswordStrength(this.value);
            });
            
            // 注册表单提交
            document.getElementById('registerForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const username = document.getElementById('reg-username').value;
                const password = document.getElementById('reg-password').value;
                const confirmPassword = document.getElementById('reg-confirm-password').value;
                const email = document.getElementById('reg-email').value;
                const captcha = document.getElementById('reg-captcha').value;
                
                if (!username || !password || !confirmPassword || !email || !captcha) {
                    showMessage('register-message', '请填写所有字段', true);
                    return;
                }
                
                if (captcha.toLowerCase() !== localStorage.getItem('captcha')?.toLowerCase()) {
                    showMessage('register-message', '验证码错误', true);
                    refreshCaptcha('reg');
                    return;
                }
                
                const usernameRegex = /^[a-zA-Z0-9]{4,16}$/;
                if (!usernameRegex.test(username)) {
                    showMessage('register-message', '用户名必须是4-16位字母或数字', true);
                    return;
                }
                
                const passwordStrengthEl = document.getElementById('reg-strength');
                if (passwordStrengthEl && passwordStrengthEl.className.includes('strength-weak')) {
                    showMessage('register-message', '密码强度不足，请使用更强的密码', true);
                    return;
                }
                
                if (password !== confirmPassword) {
                    showMessage('register-message', '两次输入的密码不一致', true);
                    return;
                }
                
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    showMessage('register-message', '请输入有效的邮箱地址', true);
                    return;
                }
                
                const users = getUsers();
                if (users.some(user => user.username === username)) {
                    showMessage('register-message', '用户名已存在，请选择其他用户名', true);
                    return;
                }
                
                if (users.some(user => user.email === email)) {
                    showMessage('register-message', '该邮箱已被注册', true);
                    return;
                }
                
                const encryptedPassword = encrypt(password);
                
                const newUser = {
                    username,
                    password: encryptedPassword,
                    email,
                    registeredAt: new Date().toISOString()
                };
                
                const updatedUsers = [...users, newUser];
                saveUsers(updatedUsers);
                
                showMessage('register-message', '注册成功！请登录', false);
                
                setTimeout(() => {
                    switchTab('login');
                }, 3000);
            });
            
            // 登录表单提交（已修改，添加跳转逻辑）
            document.getElementById('loginForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const username = document.getElementById('login-username').value;
                const password = document.getElementById('login-password').value;
                const captcha = document.getElementById('login-captcha').value;
                
                if (!username || !password || !captcha) {
                    showMessage('login-message', '请填写所有字段', true);
                    return;
                }
                
                if (captcha.toLowerCase() !== localStorage.getItem('captcha')?.toLowerCase()) {
                    showMessage('login-message', '验证码错误', true);
                    refreshCaptcha('login');
                    return;
                }
                
                const encryptedPassword = encrypt(password);
                const users = getUsers();
                const user = users.find(user => user.username === username && user.password === encryptedPassword);
                
                if (!user) {
                    showMessage('login-message', '用户名或密码错误', true);
                    return;
                }
                
                saveCurrentUser(user);
                showMessage('login-message', '登录成功！', false);
                
                // 新增：登录成功后跳转到个人详情页（假设文件名为"个人详情.html"）
                setTimeout(() => {
                    alert(`欢迎回来，${user.username}!`);
                    window.location.href = "index3.html";
                }, 1000);
            });
            
            // 发送邮箱验证码
            document.getElementById('send-code-btn')?.addEventListener('click', function() {
                const email = document.getElementById('forgot-email').value;
                if (!email) {
                    showMessage('forgot-message', '请输入邮箱地址', true);
                    return;
                }
                
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    showMessage('forgot-message', '请输入有效的邮箱地址', true);
                    return;
                }
                
                const users = getUsers();
                const user = users.find(user => user.email === email);
                if (!user) {
                    showMessage('forgot-message', '该邮箱未注册', true);
                    return;
                }
                
                // 生成随机验证码
                const emailCode = generateEmailCode();
                localStorage.setItem(EMAIL_CODE_KEY, JSON.stringify({
                    code: emailCode,
                    email: email,
                    expiresAt: Date.now() + 60000 // 1分钟有效期
                }));
                
                // 倒计时
                let countdown = 60;
                this.disabled = true;
                this.textContent = `重新发送(${countdown}s)`;
                
                const timer = setInterval(() => {
                    countdown--;
                    this.textContent = `重新发送(${countdown}s)`;
                    
                    if (countdown <= 0) {
                        clearInterval(timer);
                        this.disabled = false;
                        this.textContent = '获取验证码';
                    }
                }, 1000);
                
                showMessage('forgot-message', `验证码已发送到 ${email}，有效期1分钟`, false);
                console.log('邮箱验证码:', emailCode); // 仅用于演示，实际应用中不会显示
            });
            
            // 忘记密码表单提交
            document.getElementById('forgotForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const email = document.getElementById('forgot-email').value;
                const code = document.getElementById('forgot-code').value;
                const password = document.getElementById('forgot-password').value;
                const confirmPassword = document.getElementById('forgot-confirm-password').value;
                
                if (!email || !code || !password || !confirmPassword) {
                    showMessage('forgot-message', '请填写所有字段', true);
                    return;
                }
                
                // 验证邮箱验证码
                const storedCodeData = JSON.parse(localStorage.getItem(EMAIL_CODE_KEY) || '{}');
                if (!storedCodeData.code || storedCodeData.email !== email || storedCodeData.code !== code) {
                    showMessage('forgot-message', '验证码错误', true);
                    return;
                }
                
                // 检查验证码是否过期
                if (storedCodeData.expiresAt < Date.now()) {
                    showMessage('forgot-message', '验证码已过期，请重新获取', true);
                    return;
                }
                
                if (password !== confirmPassword) {
                    showMessage('forgot-message', '两次输入的密码不一致', true);
                    return;
                }
                
                // 更新用户密码
                const users = getUsers();
                const userIndex = users.findIndex(user => user.email === email);
                
                if (userIndex === -1) {
                    showMessage('forgot-message', '用户不存在', true);
                    return;
                }
                
                const encryptedPassword = encrypt(password);
                users[userIndex].password = encryptedPassword;
                saveUsers(users);
                
                // 清除验证码
                localStorage.removeItem(EMAIL_CODE_KEY);
                
                showMessage('forgot-message', '密码重置成功，请使用新密码登录', false);
                
                setTimeout(() => {
                    switchTab('login');
                }, 3000);
            });
        });
    </script>
</body>
</html>